<template>
  <div>
    <a-form :form="form" ref="roleUser">
      <f-form-item label="用户列表" type="other" name="user">
        <a-transfer
          :dataSource="selectUsers"
          :listStyle="{width: '45%',height: '480px'}"
          :titles="['选择用户', '已选择用户']"
          :render="item=>item.title"
          :target-keys="formItem.userIds"
          @change="handleTransferChange"
          filterable>
        </a-transfer>
      </f-form-item>
    </a-form>
  </div>
</template>

<script>
  import { getRoleUsers, getAllUsers } from '@/api/manage'

  export default {
    name: 'RoleUser',
    components: {},
    data () {

      return {
        form: this.$form.createForm(this),
        selectApis: [],
        selectMenus: [],
        selectUsers: [],
        formItem: {
          roleId: '',
          userIds: []
        }
      }
    },
    methods: {
      setData (data) {
        if (data && data.roleId) {
          this.formItem.roleId = data.roleId
          this.handleLoadRoleUsers(data.roleId)
        }
      },
      handleSubmit () {
        this.http.post(this, {
          url: this.api.role.setUser,
          data: {
            roleId: this.formItem.roleId,
            userIds: this.formItem.userIds.join(',')
          },
          success: function (me) {
            me.$bus.emit('closeModal')
          }
        })

      },
      handleLoadRoleUsers (roleId) {
        if (!roleId) {
          return
        }
        const that = this
        const p1 = getAllUsers()
        const p2 = getRoleUsers(roleId)
        Promise.all([p1, p2]).then(function (values) {
          let res1 = values[0]
          let res2 = values[1]
          if (res1.code === that.http.HTTP_OK_STATUS) {
            res1.data.map(item => {
              item.key = item.userId
              item.title = `${item.userName}(${item.nickName})`
            })
            that.selectUsers = res1.data
          }
          if (res2.code === that.http.HTTP_OK_STATUS) {
            let userIds = []
            res2.data.map(item => {
              if (!userIds.includes(item.userId)) {
                userIds.push(item.userId)
              }
            })
            that.formItem.userIds = userIds
          }
        })
      },
      handleTransferChange (targetKeys, direction, moveKeys) {
        this.formItem.userIds = targetKeys
      }
    },
    mounted: function () {
    }
  }
</script>
